#!/usr/bin/env perl
#
# watchpid
#
# */1 * * * * /usr/bin/lockf -t 0 /home/s/tmp/watchpid.lock /home/s/bin/watchpid >/dev/null 2>/dev/null
#

use	strict;
use	warnings;

my	@dir_proc=('/home/s/var/proc', );

my	$dir_crash = '/home/s/var/crash';
chdir $dir_crash;

foreach my $dir_proc (@dir_proc) {
    my	@pids = <$dir_proc/*.pid>;

    for ( @pids ) {
        next unless m/\.(\d+)\.pid$/;
        my	$pid = $1;
        my 	$alive = 0;
        for (my $retry=0; $retry<3; $retry++) {
            $alive = 1;
            my	$ok = kill( 0, $pid );
            last if $ok;

            sleep 1;
            $alive = 0;
        }
        next if $alive;

        #print "$pid is dead.\n";
        open (FH, $_) or next;
        my	$cmd = <FH>;
        close ( FH );

        my	$hostname = `uname -n`;
        chomp $hostname;
        `echo "$pid ($_) is dead, restart it. ($cmd)" | mail -s "apps restart on $hostname" admin\@example.net,admin\@example.net`;
        unlink $_;

        my	$result = `$cmd`;
    }
}


